#!/usr/bin/python
# -*- coding: UTF-8 -*-

import cv2
import halcon as ha
import time
import os

class DataMatrix:
    def __init__(self, timeout=60, max_count=1):
        """
        :param timeout 最大读取时间：单位毫秒
        :param max_count 读取的次数或深度
        """
        self.timeout = timeout
        self.max_count = max_count
        # 类型和对应的函数名
        # 扩展读取其他的码：在下方增加类型名和函数名；底部增加函数，格式如同_get_code_data_matrix

    def get_code(self, img):
        b = ''
        imgname = b.join(str(time.time()).split('.')) + '.png'
        # print(imgname)
        cv2.imwrite(imgname, img)
        img = ha.read_image(imgname)
        img = ha.scale_image(img, 2.05645, -74)
        handle = ha.create_data_code_2d_model("Data Matrix ECC 200", [], [])
        handlenew = ha.set_data_code_2d_param(handle, 'default_parameters', 'enhanced_recognition')
        code = ha.find_data_code_2d(img, handle, [], [])[-1]
        # print(code)
        os.remove(imgname)
        if len(code) > 0:
            print(code[0])
            return code[0]
        raise Exception('barcode is not found')
